<?php if (!defined('TL_ROOT')) die('You cannot access this file directly!');

/**
 * Contao Open Source CMS
 * Copyright (C) 2005-2011 Leo Feyer
 *
 * Formerly known as TYPOlight Open Source CMS.
 *
 * This program is free software: you can redistribute it and/or
 * modify it under the terms of the GNU Lesser General Public
 * License as published by the Free Software Foundation, either
 * version 3 of the License, or (at your option) any later version.
 * 
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
 * Lesser General Public License for more details.
 * 
 * You should have received a copy of the GNU Lesser General Public
 * License along with this program. If not, please visit the Free
 * Software Foundation website at <http://www.gnu.org/licenses/>.
 *
 * PHP version 5
 * @copyright  2011 Andreas Koob 
 * @author     Andreas Koob 
 * @package    tasks 
 * @license    LGPL 
 * @filesource
 */


/**
 * Class taskreader 
 *
 * @copyright  2011 Andreas Koob 
 * @author     Andreas Koob 
 * @package    Controller
 */
class tm_taskreader extends ContentElement
{

	/**
	 * Template
	 * @var string
	 */
	protected $strTemplate = 'tm_taskreader';

	private functions;
	private member = array();
	
	public function generate()
	{
		if (TL_MODE == 'BE')
		{
			$return="Tasks - Tasks reader";
			return $return;
		}
		return parent::generate();
	}

	public function processForm()
	{
		if($this->Input->post('mode')=="new")
		{
			//prepare array to save changes
			$changes=array(
				'changed'=>0,
				'labels'=>array('changed'=>0,'added_changed'=>0,'removed_changed'=>0,'added'=>array(),'removed'=>array()),
				'type'=>array('changed'=>0,'added_changed'=>0,'removed_changed'=>0,'added'=>array(),'removed'=>array()),
				'owners'=>array('changed'=>0,'added_changed'=>0,'removed_changed'=>0,'added'=>array(),'removed'=>array()),
				'ccs'=>array('changed'=>0,'added_changed'=>0,'removed_changed'=>0,'added'=>array(),'removed'=>array()),
				'priority'=>array('changed'=>0,'added_changed'=>0,'removed_changed'=>0,'added'=>array(),'removed'=>array()),
				'status'=>array('changed'=>0,'added_changed'=>0,'removed_changed'=>0,'added'=>array(),'removed'=>array()),
				'status_type'=>array('changed'=>0,'added_changed'=>0,'removed_changed'=>0,'added'=>array(),'removed'=>array())
			);
			$newComment=array(
				'description'=>$this->Input->post('description'),
				'type'=>$this->Input->post('type'),
				'labels'=>$this->Input->post('labels'),
				'priority'=>$this->Input->post('priority'),
				'owners'=>$this->Input->post('owners'),
				'ccs'=>$this->Input->post('ccs'),
				'status'=>$this->Input->post('status')
			);
			//Get the current state of the task
			$currentTask = $this->Database->prepare("SELECT * FROM tl_tm_tasks WHERE id=?")->executeUncached($taskid);
			
			//Check for changes in type and update $changes
			if($newComment['type']!=$currentTask->task_type){
				$changes['changed']=1;
				$changes['type']['changed']=1;
				$changes['type']['added_changed']=1;
				$changes['type']['removed_changed']=1;
				$changes['type']['added']=$newComment['type'];
				$changes['type']['removed']=$currentTask->task_type;
			}
			
			//check for changes in priority and update $changes
			if($newComment['priority']!=$currentTask->priority){
				$changes['changed']=1;
				$changes['priority']['changed']=1;
				$changes['priority']['added_changed']=1;
				$changes['priority']['removed_changed']=1;
				$changes['priority']['added']=$newComment['priority'];
				$changes['priority']['removed']=$currentTask->priority;
			}
			
			//check for changes in status and update $changes
			if($newComment['status']!=$currentTask->status){
				$currentStatus_type = $this->Database->prepare("SELECT status_type FROM tl_tm_statuses WHERE id=?")->executeUncached($currentTask->status);
				$newStatus_type = $this->Database->prepare("SELECT status_type FROM tl_tm_statuses WHERE id=?")->executeUncached($newComment['status']);
				$changes['changed']=1;
				$changes['status']['changed']=1;
				$changes['status']['added_changed']=1;
				$changes['status']['removed_changed']=1;
				$changes['status']['added']=$newComment['status'];
				$changes['status']['removed']=$currentTask->status;
				$changes['status_type']['changed']=1;
				$changes['status_type']['added_changed']=1;
				$changes['status_type']['removed_changed']=1;
				$changes['status_type']['added']=$newStatus_type->status_type;
				$changes['status_type']['removed']=$currentStatus_type->status_type;
			}
			
			//check for changes in labels and update $changes
			$oldlabels=unserialize($currentTask->labels);
			//check if labels have been removed
			
			if(is_array($oldlabels))
			{
				$arrDiff=$this->functions->checkForChangedEntries($oldlabels,$newComment['labels']);
				if($arrDiff['changed']==1){$changes['changed']=1;}
				$changes['labels']=$arrDiff;
			}
			
			//check for changes in owner and update $changes
			$oldowners=unserialize($currentTask->owners);
			//check if owners have been removed
			if(is_array($oldowners))
			{
				$arrDiff=$this->functions->checkForChangedEntries($oldowners,$newComment['owners']);
				if($arrDiff['changed']==1){$changes['changed']=1;}
				$changes['owners']=$arrDiff;
				}
			}
			
			//check for changes in ccs and update $changes
			$oldccs=unserialize($currentTask->ccs);
			//check if ccs have been removed
			if(is_array($oldccs))
			{
				$arrDiff=$this->functions->checkForChangedEntries($oldccs,$newComment['ccs']);
				if($arrDiff['changed']==1){$changes['changed']=1;}
				$changes['ccs']=$arrDiff;
			}
			
			
			
			//Add comment to database
			$objCommentno = $this->Database->prepare('SELECT max(comment_no) as max_comments FROM tl_tm_comments WHERE pid=?')->execute($this->Input->post('taskid'));
			$arrSetcomment = array
			(
				'pid' => $this->Input->post('taskid'),
				'comment_no' => $objCommentno->max_comments+1,
				'created_user' => $this->Input->post('userid'),
				'created_time' => time(),
				'created_date' => time(),
				'description' => $this->Input->post('description'),
			);
			if($changes['changed']==1)
			{
				$arrSetcomment['task_changed']='1';
				
				if($changes['type']['changed']==1)
				{
					$arrSetcomment['changes_type']=$changes['type'];
				}
				if($changes['priority']['changed']==1)
				{
					$arrSetcomment['changes_priority']=$changes['priority'];
				}
				if($changes['labels']['changed']==1)
				{
					$arrSetcomment['changes_labels']=$changes['labels'];
				}
				if($changes['status']['changed']==1)
				{
					$arrSetcomment['changes_status']=$changes['status'];
				}
				if($changes['status_type']['changed']==1)
				{
					$arrSetcomment['changes_status_type']=$changes['status_type'];
				}
				if($changes['owners']['changed']==1)
				{
					$arrSetcomment['changes_owners']=$changes['owners'];
				}
				if($changes['ccs']['changed']==1)
				{
					$arrSetcomment['changes_ccs']=$changes['ccs'];
				}
				
			}
			else
			{
				$arrSetcomment['task_changed']="";
			}
			
			$insertId = $this->Database->prepare("INSERT INTO tl_tm_comments %s")->set($arrSetcomment)->execute()->insertId;
			
			//Updatetask
			$arrSettask = array
			(
				'id' => $this->Input->post('taskid'),
				'labels' => serialize($this->Input->post('labels')),
				'type' => $this->Input->post('type'),
				'status' => $this->Input->post('status'),
				'status_type' => $newStatus_Type->status_type,
				'owners' => serialize($this->Input->post('owners')),
				'ccs' => serialize($this->Input->post('ccs')),
				'priority' => $this->Input->post('priority'),
			);
			$updateId = $this->Database->prepare("UPDATE tl_tm_tasks SET labels=?, task_type=?, status=?, status_type=?,  owners=?, ccs=?, priority=? WHERE id=?")->execute($arrSettask['labels'],$arrSettask['type'],$arrSettask['status'],$arrSettask['status_type'],$arrSettask['owners'],$arrSettask['ccs'],$arrSettask['priority'],$arrSettask['id']);
		}
	}
	/**
	 * Generate module
	 */
	protected function compile()
	{
		$this->functions = new tm_functions();
		
		if($this->tm_use_fixed_task=='1'){
			$taskid = $this->tm_fixed_task;
		}
		else
		{
			$taskid = $this->Input->get('task');
		}
		
		//Process form
		if($this->Input->post('submit'))
		{
			$this->processForm();	
		}
		
		
		
		$objTask = $this->Database->prepare("SELECT * FROM tl_tm_tasks WHERE id=?")->executeUncached($taskid);
		$objCreator=$this->Database->prepare("SELECT * FROM tl_member WHERE id=?")->execute($objTask->created_user);
		$task=array(
			'id'=>$taskid,
			'created_user'=>$objCreator->firstname . ' ' .  $objCreator->lastname,
			'created_date'=>date($GLOBALS['TL_CONFIG']['dateFormat'],$objTask->created_date),
			'created_time'=>date($GLOBALS['TL_CONFIG']['timeFormat'],$objTask->created_time),
			'name'=>$objTask->name,
			'description'=>$objTask->description,
			'changed'=>$objTask->changed,
			'status'=>$objTask->status,
			'status_type'=>$objTask->status_type,
			'labels'=>unserialize($objTask->labels),
			'task_type'=>$objTask->task_type,
			'owners'=>unserialize($objTask->owners),
			'ccs'=>unserialize($objTask->ccs),
			'priority'=>$objTask->priority
		);

		$objComments = $this->Database->prepare("SELECT * FROM tl_tm_comments WHERE pid=? ORDER BY comment_no ASC")->execute($taskid);
		$i=0;
		while($objComments->next()){
				$i++;
				$objCreator=$this->Database->prepare("SELECT * FROM tl_member WHERE id=?")->execute($objComments->created_user);
				$objChangeUser=$this->Database->prepare("SELECT * FROM tl_member WHERE id=?")->execute($objComments->last_change_user);
				$arrComments[]=array(
				'id'=>$objComments->id,
				'class'=>(($i == 1) ? 'first ' : '') . (($i == $objComments->numRows) ? 'last ' : '') . ((($i % 2) == 0) ? 'even' : 'odd'),
				'comment_no'=>$objComments->comment_no,
				'created_user'=>$objCreator->firstname . ' ' .  $objCreator->lastname,
				'created_date'=>date($GLOBALS['TL_CONFIG']['dateFormat'],$objComments->created_date),
				'created_time'=>date($GLOBALS['TL_CONFIG']['timeFormat'],$objComments->created_time),
				'description'=>$objComments->description,
				'task_changed'=>$objComments->task_changed,
				'changes_owners'=>unserialize($objComments->changes_owners),
				'changes_ccs'=>unserialize($objComments->changes_ccs),
				'changes_status'=>unserialize($objComments->changes_status),
				'changes_status_type'=>unserialize($objComments->changes_status_type),
				'changes_labels'=>unserialize($objComments->changes_labels),
				'changes_type'=>unserialize($objComments->changes_type),
				'changes_priority'=>unserialize($objComments->changes_priority),
				'changed'=>$objComments->changed,
				'last_change_user'=>$objChangeUser->firstname . ' ' .  $objChangeUser->lastname,
				'last_change_date'=>date($GLOBALS['TL_CONFIG']['dateFormat'],$objComments->last_change_date),
				'last_change_time'=>date($GLOBALS['TL_CONFIG']['timeFormat'],$objComments->last_change_time),
				'last_change_reason'=>$objComments->last_change_reason
				);
		}
		$this->Template->comments=$arrComments;
		
		$objTypes=$this->Database->prepare("SELECT * FROM tl_tm_types ORDER BY name ASC")->execute();
		while($objTypes->next()){
			
			if($objTypes->id==$task['task_type']){
				$selected=1;
			}
			else
			{
				$selected=0;
			}
			$arrTypes[$objTypes->id]=array(
				'id'=>$objTypes->id,
				'name'=>$objTypes->name,
				'selected'=>$selected
			);
		}
		$this->Template->types=$arrTypes;
		
		$objLabels=$this->Database->prepare("SELECT * FROM tl_tm_labels ORDER BY name ASC")->execute();
		while($objLabels->next()){
			if(is_array($task['labels']))
			{
				if(in_array($objLabels->id,$task['labels'])){
					$selected=1;
				}
				else
				{
					$selected=0;
				}
			}
			else
			{
				$selected=0;
			}
			$arrLabels[$objLabels->id]=array(
				'id'=>$objLabels->id,
				'name'=>$objLabels->name,
				'selected'=>$selected
			);
		}
		$this->Template->labels=$arrLabels;
		
		$objPriorities=$this->Database->prepare("SELECT * FROM tl_tm_priorities ORDER BY priority_order DESC, name ASC")->execute();
		while($objPriorities->next()){
			if($objPriorities->id==$task['priority']){
				$selected=1;
			}
			else
			{
				$selected=0;
			}
			$arrPriorities[$objPriorities->id]=array(
				'id'=>$objPriorities->id,
				'name'=>$objPriorities->name,
				'selected'=>$selected
			);
		}
		$this->Template->priorities=$arrPriorities;
		
		$objOwners=$this->Database->prepare("SELECT * FROM tl_member ORDER BY firstname ASC, lastname ASC, username ASC")->execute();
		while($objOwners->next()){
			if(is_array($task['owners']))
			{
				if(in_array($objOwners->id,$task['owners'])){
					$selected=1;
				}
				else
				{
					$selected=0;
				}
			}
			else
			{
				$selected=0;
			}
			$arrOwners[$objOwners->id]=array(
					'id'=>$objOwners->id,
					'firstname'=>$objOwners->firstname,
					'lastname'=>$objOwners->lastname,
					'username'=>$objOwners->username,
					'selected'=>$selected
				);
		}
		$this->Template->owners=$arrOwners;
		
		$objCCS=$this->Database->prepare("SELECT * FROM tl_member ORDER BY firstname ASC, lastname ASC, username ASC")->execute();
		while($objCCS->next()){
			if(is_array($task['ccs']))
			{
				if(in_array($objCCS->id,$task['ccs'])){
					$selected=1;
				}
				else
				{
					$selected=0;
				}
			}
			else
			{
				$selected=0;
			}
			$arrCCs[$objCCS->id]=array(
				'id'=>$objCCS->id,
				'firstname'=>$objCCS->firstname,
				'lastname'=>$objCCS->lastname,
				'username'=>$objCCS->username,
				'selected'=>$selected
			);
		}
		$this->Template->ccs=$arrCCs;
		
		$objStatuses=$this->Database->prepare("SELECT * FROM tl_tm_statuses ORDER BY name ASC")->execute();
		while($objStatuses->next()){
			if($objStatuses->id==$task['status']){
				$selected=1;
			}
			else
			{
				$selected=0;
			}
			switch($objStatuses->status_type)
			{
				case "O":
					$arrOpenStatuses[]=array(
						'id'=>$objStatuses->id,
						'name'=>$objStatuses->name,
						'selected'=>$selected
					);
					break;
				case "W":
					$arrWorkingStatuses[]=array(
						'id'=>$objStatuses->id,
						'name'=>$objStatuses->name,
						'selected'=>$selected
					);
					break;
				case "C":
					$arrClosedStatuses[]=array(
						'id'=>$objStatuses->id,
						'name'=>$objStatuses->name,
						'selected'=>$selected
					);
					break;
				default:
					$arrOpenStatuses[]=array(
						'id'=>$objStatuses->id,
						'name'=>$objStatuses->name,
						'selected'=>$selected
					);
			}
			$arrStatuses[$objStatuses->id]=array(
				'id'=>$objStatuses->id,
				'name'=>$objStatuses->name,
				'selected'=>$selected
			);
		}
		$this->Template->statuses=$arrStatuses;
		$this->Template->open_statuses=$arrOpenStatuses;
		$this->Template->working_statuses=$arrWorkingStatuses;
		$this->Template->closed_statuses=$arrClosedStatuses;
		$this->Template->status_types=array('O'=>'Open Tasks','W'=>'Working Tasks','C'=>'Closed Tasks');
		$this->Template->task=$task;
		
		$this->member=$this->functions->getMemberInformation();
		$this->Template->member=$this->member;
			
		$objProject=$this->Database->prepare("SELECT * FROM tl_tm_projects WHERE id=?")->execute($objTask->pid);
		$this->Template->project_adv_creator=unserialize($objProject->adv_creator_groups);
	}
}

?>